package com.example.tangyee.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.tangyee.R;
import com.example.tangyee.adapter.MyRecyclerViewAdapter;
import com.example.tangyee.bean.HealthVideo;
import com.example.tangyee.utils.GetHealthVideos;
import com.example.tangyee.utils.GlideApp;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jzvd.JZMediaManager;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdMgr;
import cn.jzvd.JzvdStd;

public class HealthVideosActivity extends AppCompatActivity {

    private static final String TAG = "HealthVideosActivity";

    private Unbinder mUnbinder;

    @BindView(R.id.health_video_back)
    LinearLayout back;
    @BindView(R.id.health_video_title)
    TextView title;

    @BindView(R.id.video_recycler_view)
    RecyclerView mRecyclerView;

    private MyRecyclerViewAdapter<HealthVideo> mAdapter;
    private List<HealthVideo> data = new ArrayList<>();
    private View footView;
    private LinearLayoutManager layoutManager;

    private GetHealthVideos mGetHealthVideos;

    private boolean isLoading = false;

    boolean isClear = false;

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_videos);
        mUnbinder = ButterKnife.bind(this);

        /*
         * 下拉刷新
         * */
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mGetHealthVideos != null) {
                mGetHealthVideos.cancel(true);
            }
            ProgressBar progressBar = footView.findViewById(R.id.progressBar);
            progressBar.setVisibility(View.GONE);
            TextView textView = footView.findViewById(R.id.loading);
            textView.setText("努力加载中···");
            isClear = true;
            mGetHealthVideos = new GetHealthVideos( 1, 10, execute);
            mGetHealthVideos.execute();
        });

        // 初始化RecyclerView
        initRecyclerView();
    }

    GetHealthVideos.OnPostExecute execute;
    private void initRecyclerView() {
        mAdapter = new MyRecyclerViewAdapter<>(data, this, R.layout.video_item_list_layout);
        footView = LayoutInflater.from(this).inflate(R.layout.item_foot_layout,null);
        mAdapter.addFooterView(footView);
        mAdapter.setItemViewHelper(new MyRecyclerViewAdapter.ItemViewHelper<HealthVideo>() {
            @Override
            public void onClick(View view, HealthVideo video) {
                HealthVideoPlayerActivity.gotoHealthVideoPlayerActivity(HealthVideosActivity.this, video);
            }

            @Override
            public void onBindViewHolder(MyRecyclerViewAdapter.MyHolder holder, int position, HealthVideo video) {
                TextView title = holder.itemView.findViewById(R.id.title);
                title.setText(video.getTitle());
                TextView heat = holder.itemView.findViewById(R.id.heat);
                heat.setText(video.getHeat());

                ImageView image = holder.itemView.findViewById(R.id.video_image);
                GlideApp.with(HealthVideosActivity.this)
                        .load(video.getImageUrl())
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.error)
                        .fitCenter()
                        .into(image);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);

        execute = items -> {
            if (items == null) {
                if (refreshLayout != null)
                    refreshLayout.finishRefresh(false);
                ProgressBar progressBar = footView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = footView.findViewById(R.id.loading);
                textView.setText("请求超时···");
            } else if (items.size() == 0) {
                if (refreshLayout != null)
                    refreshLayout.finishRefresh(true);
                ProgressBar progressBar = footView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = footView.findViewById(R.id.loading);
                textView.setText("没有数据了···");
            } else {
                if (refreshLayout != null)
                    refreshLayout.finishRefresh(true);
                int count = mAdapter.getItemCount();
                mAdapter.updateDate(items, isClear);

                if (count <= 1 || isClear) {
                    isClear = false;
                    ScaleAnimation sa = new ScaleAnimation(1f, 1f, 1.1f, 1f,
                            Animation.RELATIVE_TO_SELF, 0f,
                            Animation.RELATIVE_TO_SELF, 0f);
                    sa.setDuration(1000);

                    AlphaAnimation aa = new AlphaAnimation(0, 1);
                    aa.setDuration(1000);

                    AnimationSet as = new AnimationSet(true);
                    as.setDuration(1000);
                    as.addAnimation(sa);
                    as.addAnimation(aa);

                    mRecyclerView.startAnimation(as);
                }
            }

            // 设置为false,表示可以再次请求数据了
            isLoading = false;

            isLoading = true;

            {
                ProgressBar progressBar = footView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = footView.findViewById(R.id.loading);
                textView.setText("没有数据了···");
            }
        };

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == mAdapter.getItemCount() && !isLoading) { // footItem 可见时，说明该加载更多了。
                    Log.d("test", "loading executed");
                    isLoading = true;
                    mGetHealthVideos = new GetHealthVideos( 1, 10, execute);
                    mGetHealthVideos.execute();
                }
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                try {
                    /*glide优化，提升性能?*/
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        GlideApp.with(HealthVideosActivity.this).resumeRequests();
                    } else {
                        GlideApp.with(HealthVideosActivity.this).pauseRequests();
                    }
                } catch (IllegalArgumentException iae) {
                    Log.e(TAG, "onScrollStateChanged: ", iae);
                }
            }
        });

    }

    @OnClick(R.id.health_video_back)
    public void back(View view) {
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGetHealthVideos != null) {
            mGetHealthVideos.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
